#include "Metgine/Core/Math.hpp"
#include "Metgine/Core/Intersection.hpp"
//#include "Metgine/Core/Renderer.hpp"

using namespace Math;

namespace Metgine
{

namespace Core
{


Intersection::Intersection() :
    object(NULL),
    position(Vector2f(INFINITY, INFINITY)),
    distance(INFINITY),
    type(IntersectionType::None)
{
}

/*
    Geometric Intersection Tests
*/

bool RayCircleIntersection(const Vector2f& rayStart, const Vector2f& rayDirection, const Vector2f& circleCenter, float circleRadius, float maxRange, Vector2f& intersection)
{

    Vector2f circleToRay = circleCenter - rayStart;
    float d = DotProduct(rayDirection, circleToRay);

    if ((d > maxRange) || (d < 0.0f))
        return false;

    Vector2f pointOnRay = rayStart + rayDirection * d;
    float t = (pointOnRay - circleCenter).Length();

    if (t > circleRadius)
        return false;
    else if (t == circleRadius)
    {

        // One intersection
        intersection = pointOnRay;
        return true;

    }
    else
    {

        // Two intersections, return the one nearest to the ray start
        float x = Math::Sqrt(circleRadius * circleRadius - t * t);
        intersection = pointOnRay - rayDirection * x;

        return true;

    }

}

bool BoxBoxIntersection(const BoundingBoxf& a, const BoundingBoxf& b)
{

    Vector2f minA = a.GetMin();
    Vector2f maxA = a.GetMax();

    Vector2f minB = b.GetMin();
    Vector2f maxB = b.GetMax();

    if ((maxA.y < minB.y) || (minA.y > maxB.y) || (maxA.x < minB.x) || (minA.x > maxB.x))
        return false;

    return true;

}

}; // Core
}; // Metgine
